import React, {Component} from 'react';
import moment from 'moment';
import {connect} from 'dva';
import {
	Form,
	Card,
	Select,
	List,
	Icon,
	Row,
	Col,
	Button,
	Avatar,
	Input,
	Affix,
	Tooltip
} from 'antd';

import Ellipsis from 'components/Ellipsis';
import StandardFormRow from 'components/StandardFormRow';
import styles from './List.less';
import replyStyles from './Reply.less';

import InfiniteScroll from 'react-infinite-scroller';

const {Option} = Select;
const FormItem = Form.Item;

const pageSize = 8;

@Form.create()
@connect(({article, comment, loading}) => ({list: article.list, comment: comment.list, authors: article.authors, loading: loading.models.list}))
export default class Reply extends Component {
	state = {
		page: 1,
		replyPage: 1,
		reply: {},
		replyArticleId: 0,
		loading: false,
		hasMore: true,
		formValues: {}
	};
	componentDidMount() {
		this.fetchAuthor();
		this.fetchMore();
		// this.fetchComment(this.state.replyArticleId);
	};
	setOwner = () => {
		const {form} = this.props;
		form.setFieldsValue({owner: ['wzj']});
	};
	fetchAuthor = () => {
		this.props.dispatch({type: 'article/fetchAuthor', payload: {}});
	};
	fetchComment = () => {
		if (this.state.replyPage === 1) {
			this.props.dispatch({
				type: 'comment/fetchComment',
				payload: {
					article_id: this.state.replyArticleId,
					page: this.state.replyPage
				}
			});
		} else {
			this.props.dispatch({
				type: 'comment/fetchMoreComment',
				payload: {
					article_id: this.state.replyArticleId,
					page: this.state.replyPage
				}
			});
		}
		this.setState({
			loading: true,
			hasMore: true,
			replyPage: this.state.replyPage + 1
		});
	};
	fetchotherArticleComment = articleId => {
		this.props.dispatch({
			type: 'comment/fetchComment',
			payload: {
				article_id: articleId,
				page: 1
			}
		});

		this.setState({loading: false, hasMore: true, replyArticleId: articleId, replyPage: 2});
	};

	fetchMore = () => {
		if (this.state.page === 1) {
			this.props.dispatch({
				type: 'article/fetch',
				payload: {
					count: pageSize,
					page: this.state.page,
					...this.state.formValues
				}
			});
		} else {
			this.props.dispatch({
				type: 'article/appendFetch',
				payload: {
					count: pageSize,
					page: this.state.page,
					...this.state.formValues
				}
			});
		}
		this.setState({
			page: this.state.page + 1
		});
	};
	handlePushComment = (e) => {
		this.props.dispatch({type: 'comment/reply', payload: this.state.reply});
		e.target.value = '';
	};
	handleChange = (e) => {
		const {value, id} = e.target;
		this.setState({
			page: 1,
			reply: {
				reply_content: value,
				comment_id: id
			}
		});
	};

	updateStatus = (id, updateStatusCode) => {
		this.props.dispatch({
			type: 'comment/status',
			payload: {
				comment_id: id,
				status: updateStatusCode
			}
		});
	};

	deleteReply = (id) => {
		this.props.dispatch({
			type: 'comment/deleteReply',
			payload: {
				comment_id: id
			}
		});
	};

	handleSearch = e => {
		e.preventDefault();

		const {dispatch, form} = this.props;

		form.validateFields((err, fieldsValue) => {
			if (err)
				return;

			const values = {
				...fieldsValue,
				updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf()
			};

			this.setState({formValues: values});

			dispatch({type: 'article/fetch', payload: values});
		});
	};

	handleFormReset = () => {
		const {form, dispatch} = this.props;
		form.resetFields();
		this.setState({formValues: {}});
		dispatch({type: 'article/fetch', payload: {}});
	};

	render() {
		const {form, list, authors, loading, comment} = this.props;
		const {getFieldDecorator} = form;
		const loadMore = list.length > 0
			? (<div style={{
					textAlign: 'center',
					marginTop: 16
				}}>
				<Button onClick={this.fetchMore} style={{
						paddingLeft: 48,
						paddingRight: 48
					}}>
					{
						loading
							? (<span>
								<Icon type="loading"/>
								加载中...
							</span>)
							: ('加载更多')
					}
				</Button>
			</div>)
			: null;
		return (<div>
			<Card bordered={false}>
				<div>
					<Form onSubmit={this.handleSearch} layout="inline">
						<Row gutter={{
								md: 8,
								lg: 24,
								xl: 48
							}}>
							<Col md={4} sm={12}>
								<FormItem label="作者">
									{
										getFieldDecorator('author_id')(<Select showSearch="showSearch" style={{
												width: 100
											}} placeholder="选择作者" optionFilterProp="children">
											{
												authors.map(author => (<Option key={author.id} value={author.id}>
													{author.nickname}
												</Option>))
											}
										</Select>)
									}
								</FormItem>
							</Col>
							<Col md={4} sm={12}>
								<span className={styles.submitButtons}>
									<Button type="primary" htmlType="submit">
										查询
									</Button>
									<Button style={{
											marginLeft: 8
										}} onClick={this.handleFormReset}>
										重置
									</Button>
								</span>
							</Col>
						</Row>
					</Form>
				</div>
			</Card>
			<Row>
				<Col span={6}>
					<div className={styles.coverCardList}>
						<List size="large" loading={list.length === 0
								? loading
								: false} rowKey="id" grid={{
								gutter: 24,
								column: 1
							}} loadMore={loadMore} dataSource={list} renderItem={item => (<List.Item style={{
									borderBottom: 'none'
								}}>
								<Card hoverable="hoverable" className={styles.card} actions={[
										<div onClick={() => this.fetchotherArticleComment(item.id)} title="获取该文章的评论">
											<Icon type="anticon anticon-message" style={{
													marginRight: 8
												}}/>{item.comment_count.all_count}
										</div>,
										<div onClick={() => this.fetchotherArticleComment(item.id)} title="放出的评价数量">
											<Icon type="eye-o" style={{
													marginRight: 8
												}}/>{item.comment_count.open_count}
										</div>
									]}>
									<Card.Meta title={item.title} description={<Ellipsis lines = {
											2
										} > {
											item.intro
										}
										</Ellipsis>}/>
									<div className={styles.cardItemContent}>
										<span>{item.author}</span>
										<span>{moment(item.create_time).fromNow()}</span>
									</div>
								</Card>
							</List.Item>)}/>
					</div>
				</Col>
				<Col span={10} style={{
						marginLeft: 50
					}}>
					<Affix>
						<div className={styles.coverCardList} style={{
								height: '46rem',
								width: '100%',
								overflow: 'auto'
							}}>
							<InfiniteScroll initialLoad={false} pageStart={0} loadMore={this.fetchComment} hasMore={!this.state.loading && this.state.hasMore} useWindow={false}>
								<List size="middle" loading={list.length === 0
										? loading
										: false} rowKey="id" grid={{
										gutter: 0,
										column: 1
									}} dataSource={comment} renderItem={item => (<div className={replyStyles.listItem}>
										<List.Item style={{
												borderBottom: 'none'
											}} actions={[
												item.status === 1
													? <Tooltip placement="top" title="关闭">
														<Button loading={this.state.statusLoading} onClick={() => this.updateStatus(item.id, 0)} icon="eye-o" type="danger"/>
													</Tooltip>
													: <Tooltip placement="top" title="放出">
														<Button loading={this.state.statusLoading} onClick={() => this.updateStatus(item.id, 1)} icon="eye" id={item.id} type="primary"/>
													</Tooltip>
											]}>
											<List.Item.Meta avatar={<Avatar src = {
													item.user_avatar
												} />} title={item.user_name} description={item.content}/>
										</List.Item>
										{
											item.reply_content
												? <div style={{
															padding: 20
														}}>
														回复@{item.user_name}: {item.reply_content}
														<Button loading={this.state.deleteReplyLoading} style={{
																marginLeft: 20
															}} onClick={() => this.deleteReply(item.id)} type="danger" size="small" icon="delete"/>
													</div>
												: ''
										}
										<Input onPressEnter={this.handlePushComment} onChange={this.handleChange} id={item.id} placeholder="回复"/>
									</div>)}/>
							</InfiniteScroll>
						</div>
					</Affix>
				</Col>
			</Row>
		</div>);
	}
}
